/**
 * 测试数据生成器
 * 为各种测试场景生成模拟数据
 */

const moment = require('moment');

class TestDataGenerator {
  constructor() {
    this.userCounter = 0;
    this.listCounter = 0;
    this.taskCounter = 0;
  }

  /**
   * 生成测试用户数据
   */
  generateTestUser(options = {}) {
    this.userCounter++;
    const timestamp = Date.now();
    
    return {
      id: options.id || `test_user_${this.userCounter}_${timestamp}`,
      username: options.username || `testuser${this.userCounter}`,
      email: options.email || `testuser${this.userCounter}@example.com`,
      password: options.password || 'TestPassword123!',
      firstName: options.firstName || `Test`,
      lastName: options.lastName || `User${this.userCounter}`,
      avatar: options.avatar || null,
      preferences: {
        theme: 'light',
        language: 'zh-CN',
        timezone: 'Asia/Shanghai',
        notifications: true,
        autoSync: true,
        pomodoroSettings: {
          workDuration: 25,
          shortBreak: 5,
          longBreak: 15,
          longBreakInterval: 4
        }
      },
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };
  }

  /**
   * 生成测试清单数据
   */
  generateTestList(options = {}) {
    this.listCounter++;
    const timestamp = Date.now();
    
    const listNames = [
      '工作任务',
      '个人事务',
      '学习计划',
      '购物清单',
      '旅行计划',
      '健身目标',
      '读书笔记',
      '项目管理'
    ];
    
    const colors = [
      '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4',
      '#FFEAA7', '#DDA0DD', '#98D8C8', '#F7DC6F'
    ];
    
    const icons = [
      'work', 'personal', 'study', 'shopping',
      'travel', 'fitness', 'book', 'project'
    ];
    
    return {
      id: options.id || `test_list_${this.listCounter}_${timestamp}`,
      name: options.name || listNames[this.listCounter % listNames.length],
      description: options.description || `这是测试清单${this.listCounter}的描述`,
      color: options.color || colors[this.listCounter % colors.length],
      icon: options.icon || icons[this.listCounter % icons.length],
      isDefault: options.isDefault || false,
      sortOrder: options.sortOrder || this.listCounter,
      taskCount: options.taskCount || 0,
      completedTaskCount: options.completedTaskCount || 0,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };
  }

  /**
   * 生成测试任务数据
   */
  generateTestTask(options = {}) {
    this.taskCounter++;
    const timestamp = Date.now();
    
    const taskTitles = [
      '完成项目报告',
      '准备会议材料',
      '回复重要邮件',
      '更新项目文档',
      '安排团队会议',
      '审核代码变更',
      '测试新功能',
      '优化系统性能',
      '备份重要数据',
      '学习新技术'
    ];
    
    const priorities = ['low', 'medium', 'high', 'urgent'];
    const statuses = ['pending', 'in_progress', 'completed', 'cancelled'];
    
    const task = {
      id: options.id || `test_task_${this.taskCounter}_${timestamp}`,
      title: options.title || taskTitles[this.taskCounter % taskTitles.length],
      description: options.description || `这是测试任务${this.taskCounter}的详细描述，包含了任务的具体要求和执行步骤。`,
      listId: options.listId || null,
      priority: options.priority || priorities[Math.floor(Math.random() * priorities.length)],
      status: options.status || 'pending',
      completed: options.completed || false,
      estimatedTime: options.estimatedTime || Math.floor(Math.random() * 240) + 30, // 30-270分钟
      actualTime: options.actualTime || 0,
      tags: options.tags || this.generateRandomTags(),
      dueDate: options.dueDate || this.generateRandomDueDate(),
      reminder: options.reminder || null,
      notes: options.notes || '',
      attachments: options.attachments || [],
      subtasks: options.subtasks || [],
      recurring: options.recurring || null,
      pomodoroCount: options.pomodoroCount || 0,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      completedAt: options.completed ? new Date().toISOString() : null
    };
    
    // 如果是重复任务，添加重复配置
    if (options.isRecurring) {
      task.recurring = this.generateRecurringConfig();
    }
    
    // 如果有子任务，生成子任务
    if (options.hasSubtasks) {
      task.subtasks = this.generateSubtasks(3);
    }
    
    return task;
  }

  /**
   * 生成随机标签
   */
  generateRandomTags() {
    const allTags = [
      '紧急', '重要', '工作', '个人', '学习',
      '会议', '电话', '邮件', '文档', '代码',
      '测试', '部署', '优化', '修复', '新功能'
    ];
    
    const tagCount = Math.floor(Math.random() * 4); // 0-3个标签
    const selectedTags = [];
    
    for (let i = 0; i < tagCount; i++) {
      const randomTag = allTags[Math.floor(Math.random() * allTags.length)];
      if (!selectedTags.includes(randomTag)) {
        selectedTags.push(randomTag);
      }
    }
    
    return selectedTags;
  }

  /**
   * 生成随机到期日期
   */
  generateRandomDueDate() {
    const daysFromNow = Math.floor(Math.random() * 30) - 5; // -5到25天
    return moment().add(daysFromNow, 'days').toISOString();
  }

  /**
   * 生成重复任务配置
   */
  generateRecurringConfig() {
    const types = ['daily', 'weekly', 'monthly', 'yearly'];
    const type = types[Math.floor(Math.random() * types.length)];
    
    const config = {
      type: type,
      interval: Math.floor(Math.random() * 3) + 1, // 1-3
      endDate: moment().add(6, 'months').toISOString()
    };
    
    if (type === 'weekly') {
      config.daysOfWeek = [1, 3, 5]; // 周一、三、五
    } else if (type === 'monthly') {
      config.dayOfMonth = Math.floor(Math.random() * 28) + 1; // 1-28号
    }
    
    return config;
  }

  /**
   * 生成子任务
   */
  generateSubtasks(count = 3) {
    const subtasks = [];
    const subtaskTitles = [
      '收集相关资料',
      '制定详细计划',
      '执行第一阶段',
      '中期检查评估',
      '完善和优化',
      '最终确认提交'
    ];
    
    for (let i = 0; i < count; i++) {
      subtasks.push({
        id: `subtask_${Date.now()}_${i}`,
        title: subtaskTitles[i % subtaskTitles.length],
        completed: Math.random() > 0.7, // 30%概率已完成
        createdAt: new Date().toISOString()
      });
    }
    
    return subtasks;
  }

  /**
   * 生成测试数据集
   */
  generateTestDataSet(options = {}) {
    const userCount = options.userCount || 1;
    const listCount = options.listCount || 5;
    const taskCount = options.taskCount || 20;
    
    const users = [];
    const lists = [];
    const tasks = [];
    
    // 生成用户
    for (let i = 0; i < userCount; i++) {
      users.push(this.generateTestUser());
    }
    
    // 生成清单
    for (let i = 0; i < listCount; i++) {
      const list = this.generateTestList();
      if (i === 0) {
        list.isDefault = true;
        list.name = '默认清单';
      }
      lists.push(list);
    }
    
    // 生成任务
    for (let i = 0; i < taskCount; i++) {
      const task = this.generateTestTask({
        listId: lists[Math.floor(Math.random() * lists.length)].id,
        isRecurring: Math.random() > 0.8, // 20%概率是重复任务
        hasSubtasks: Math.random() > 0.7, // 30%概率有子任务
        completed: Math.random() > 0.6 // 40%概率已完成
      });
      tasks.push(task);
    }
    
    // 更新清单的任务统计
    lists.forEach(list => {
      const listTasks = tasks.filter(task => task.listId === list.id);
      list.taskCount = listTasks.length;
      list.completedTaskCount = listTasks.filter(task => task.completed).length;
    });
    
    return {
      users,
      lists,
      tasks,
      metadata: {
        generatedAt: new Date().toISOString(),
        userCount: users.length,
        listCount: lists.length,
        taskCount: tasks.length
      }
    };
  }

  /**
   * 生成性能测试数据
   */
  generatePerformanceTestData() {
    return this.generateTestDataSet({
      userCount: 1,
      listCount: 20,
      taskCount: 1000
    });
  }

  /**
   * 生成边界测试数据
   */
  generateBoundaryTestData() {
    const data = {
      emptyData: {
        users: [],
        lists: [],
        tasks: []
      },
      maxLengthData: {
        user: this.generateTestUser({
          username: 'a'.repeat(50),
          email: 'a'.repeat(40) + '@example.com',
          firstName: 'a'.repeat(30),
          lastName: 'b'.repeat(30)
        }),
        list: this.generateTestList({
          name: 'a'.repeat(100),
          description: 'a'.repeat(500)
        }),
        task: this.generateTestTask({
          title: 'a'.repeat(200),
          description: 'a'.repeat(2000),
          notes: 'a'.repeat(1000)
        })
      },
      specialCharacterData: {
        user: this.generateTestUser({
          username: 'test@#$%^&*()_+',
          firstName: '测试用户',
          lastName: '特殊字符'
        }),
        list: this.generateTestList({
          name: '📋 特殊字符清单 🎯',
          description: '包含特殊字符的描述：@#$%^&*()_+{}[]|\\:;"<>?,./'
        }),
        task: this.generateTestTask({
          title: '🚀 特殊字符任务 ✅',
          description: '包含emoji和特殊字符的任务描述 🎉'
        })
      }
    };
    
    return data;
  }

  /**
   * 生成同步测试数据
   */
  generateSyncTestData() {
    const baseTime = new Date();
    
    return {
      localData: this.generateTestDataSet({ taskCount: 10 }),
      serverData: this.generateTestDataSet({ taskCount: 12 }),
      conflictData: {
        // 模拟冲突场景：同一任务在本地和服务器都有修改
        localTask: this.generateTestTask({
          id: 'conflict_task_1',
          title: '本地修改的任务',
          updatedAt: moment(baseTime).add(1, 'hour').toISOString()
        }),
        serverTask: this.generateTestTask({
          id: 'conflict_task_1',
          title: '服务器修改的任务',
          updatedAt: moment(baseTime).add(2, 'hours').toISOString()
        })
      },
      timestamps: {
        lastSync: moment(baseTime).subtract(1, 'day').toISOString(),
        currentTime: baseTime.toISOString()
      }
    };
  }

  /**
   * 生成AI测试数据
   */
  generateAiTestData() {
    return {
      prompts: [
        {
          input: '帮我制定一个学习计划',
          timeframe: '1month',
          expectedTasks: [
            '制定学习目标',
            '选择学习资源',
            '安排学习时间',
            '定期复习和总结'
          ]
        },
        {
          input: '准备下周的工作任务',
          timeframe: '1week',
          expectedTasks: [
            '回顾本周工作进度',
            '确定下周优先级',
            '安排会议和沟通',
            '准备必要的资源'
          ]
        },
        {
          input: '组织一次团队建设活动',
          timeframe: '2weeks',
          expectedTasks: [
            '确定活动主题和形式',
            '选择活动时间和地点',
            '邀请团队成员参与',
            '准备活动物料',
            '执行活动计划',
            '收集反馈和总结'
          ]
        }
      ],
      invalidPrompts: [
        '', // 空输入
        'a'.repeat(1000), // 过长输入
        '!@#$%^&*()', // 特殊字符
        '   ', // 只有空格
      ]
    };
  }

  /**
   * 生成统计测试数据
   */
  generateStatisticsTestData() {
    const tasks = [];
    const baseDate = moment().startOf('month');
    
    // 生成一个月的任务数据
    for (let day = 0; day < 30; day++) {
      const dayTasks = Math.floor(Math.random() * 5) + 1; // 每天1-5个任务
      
      for (let i = 0; i < dayTasks; i++) {
        const taskDate = moment(baseDate).add(day, 'days');
        const isCompleted = Math.random() > 0.3; // 70%完成率
        
        tasks.push(this.generateTestTask({
          createdAt: taskDate.toISOString(),
          completed: isCompleted,
          completedAt: isCompleted ? taskDate.add(Math.random() * 8, 'hours').toISOString() : null,
          estimatedTime: Math.floor(Math.random() * 120) + 30,
          actualTime: isCompleted ? Math.floor(Math.random() * 150) + 20 : 0,
          pomodoroCount: isCompleted ? Math.floor(Math.random() * 4) + 1 : 0
        }));
      }
    }
    
    return {
      tasks,
      expectedStats: {
        totalTasks: tasks.length,
        completedTasks: tasks.filter(t => t.completed).length,
        totalEstimatedTime: tasks.reduce((sum, t) => sum + t.estimatedTime, 0),
        totalActualTime: tasks.reduce((sum, t) => sum + t.actualTime, 0),
        totalPomodoroCount: tasks.reduce((sum, t) => sum + t.pomodoroCount, 0)
      }
    };
  }

  /**
   * 重置计数器
   */
  resetCounters() {
    this.userCounter = 0;
    this.listCounter = 0;
    this.taskCounter = 0;
  }
}

module.exports = TestDataGenerator;